package com.yc.web;

import com.yc.services.RedPacketService;
import com.yc.web.controller.model.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/redPacket")
public class RedPacketController {

    @Autowired
    private RedPacketService redPacketService;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 创建红包活动
     * @param totalAmount 红包总金额
     * @param totalCount 红包总数量
     * @param startTime 开始时间字符串(yyyy-MM-dd HH:mm:ss)
     * @param endTime 结束时间字符串(yyyy-MM-dd HH:mm:ss)
     * @return 响应结果
     */
    @PostMapping("/create")
    public ResponseResult createRedPacketActivity(
            @RequestParam Double totalAmount,
            @RequestParam Integer totalCount,
            @RequestParam String startTime,
            @RequestParam String endTime) {

        try {
            // 解析时间字符串
            LocalDateTime start = LocalDateTime.parse(startTime, DATE_TIME_FORMATTER);
            LocalDateTime end = LocalDateTime.parse(endTime, DATE_TIME_FORMATTER);

            // 调用服务层
            return redPacketService.createRedPacketActivity(totalAmount, totalCount, start, end);
        } catch (Exception e) {
            return ResponseResult.error("时间格式不正确，请使用yyyy-MM-dd HH:mm:ss格式");
        }
    }

    /**
     * 获取红包活动详情
     * @param activityId 活动ID
     * @return 响应结果
     */
    @GetMapping("/activity/{activityId}")
    public ResponseResult getRedPacketActivity(@PathVariable Long activityId) {
        return redPacketService.getRedPacketActivity(activityId);
    }

    /**
     * 抢红包
     * @param activityId 活动ID
     * @param userId 用户ID
     * @return 响应结果
     */
    @PostMapping("/grab/{activityId}/{userId}")
    public ResponseResult grabRedPacket(@PathVariable Long activityId, @PathVariable Long userId) {
        return redPacketService.grabRedPacket(activityId, userId);
    }

    /**
     * 获取用户红包领取记录
     * @param userId 用户ID
     * @param activityId 活动ID
     * @return 响应结果
     */
    @GetMapping("/record/{userId}/{activityId}")
    public ResponseResult getUserRedPacketRecord(
            @PathVariable Long userId,
            @PathVariable Long activityId) {

        return redPacketService.getUserRedPacketRecord(userId, activityId);
    }
}